package com.uuah.server.transport.provider.mina.codecs.server;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecException;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uuah.server.api.message.IUuahBusiMessage;
import com.uuah.server.util.UuahBusiMessageUtils;

public class UuahResponseMessageEncoder implements ProtocolEncoder {
	protected transient Logger logger = LoggerFactory.getLogger(getClass());

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws ProtocolCodecException {
		if (logger.isDebugEnabled()) {
			logger.debug("encode to UuahBusiMessage");
		}
		List<IUuahBusiMessage> list = (List<IUuahBusiMessage>) message;
		byte[] result = null;
		for (IUuahBusiMessage uuahBusiMessage : list) {
			try {
				byte[] temp = UuahBusiMessageUtils
						.encodeUuahBusiMessage(uuahBusiMessage);
				result = ArrayUtils.addAll(result, temp);
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		IoBuffer buf = IoBuffer.allocate(result.length);
		buf.put(result);
		buf.flip();
		out.write(buf);
	}

	public void dispose(IoSession session) throws Exception {

	}
}
